package com.vipheyue.educationmp4.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.tencent.bugly.crashreport.CrashReport;
import com.vipheyue.educationmp4.R;
import com.vipheyue.educationmp4.bean.GradeBean;
import com.vipheyue.educationmp4.bean.MyUser;
import com.vipheyue.educationmp4.download.DownloadActivity;
import com.vipheyue.fastlib.FastApp;
import com.vipheyue.fastlib.adapter.BaseRecyclerAdapter;
import com.vipheyue.fastlib.adapter.BaseRecyclerViewHolder;
import com.vipheyue.fastlib.utils.Log;
import com.vipheyue.fastlib.utils.SharePreferencesUtil;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobRealTimeData;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.ValueEventListener;

import static com.vipheyue.educationmp4.activity.LoginActivity.LOGINTIME;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    @Bind(R.id.recycler)
    RecyclerView recyclerView;
    ArrayList<GradeBean> mdata = new ArrayList<>();
    @Bind(R.id.toolbar_title)
    TextView toolbar_title;
    @Bind(R.id.toolbar_right)
    ImageView toolbar_right;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.content_main2)
    RelativeLayout content_main2;
    @Bind(R.id.nav_view)
    NavigationView nav_view;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawer_layout;


    private BaseRecyclerAdapter adapter;
    private MyUser myLocalUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
        initData();
        queryCommand();
        startLongListener();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        toolbar.setNavigationIcon(R.drawable.ic_save);
        toolbar_title.setText("教育");
        toolbar.setNavigationOnClickListener(view -> {
            startActivity(new Intent(MainActivity.this, DownloadActivity.class));
        });

//        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
//                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//        drawer.setDrawerListener(toggle);
//        toggle.syncState();
//
//        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
//        navigationView.setNavigationItemSelectedListener(this);
    }

    private void startLongListener() {
        BmobRealTimeData rtd = new BmobRealTimeData();
        rtd.start(this, new ValueEventListener() {
            @Override
            public void onDataChange(JSONObject data) {
                Log.d("(" + data.optString("action") + ")" + "数据：" + data);
                try {
                    Object data1 = data.get("data");
                    MyUser netUser = new Gson().fromJson(data1.toString(), MyUser.class);
                    if (netUser!=null&&myLocalUser!=null&&!netUser.getInstallationId().equals(myLocalUser.getInstallationId())) {
                        new AlertView("提醒", "你的账号已在其他地方登录", null, new String[]{"确定"}, null, MainActivity.this,
                                AlertView.Style.Alert, new OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {
                                BmobUser.logOut(MainActivity.this);   //清除缓存用户对象
                                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                                finish();
                            }
                        }).show();
                    }
                    Logger.e(netUser.getInstallationId());
                } catch (JSONException e) {
                    e.printStackTrace();
                    CrashReport.postCatchedException(e);  // bugly会将这个throwable上报

                }
            }

            @Override
            public void onConnectCompleted() {
                Log.d("连接成功:" + rtd.isConnected());
                if (rtd.isConnected()) {
                    // 监听行更新
                    rtd.subRowUpdate("_User", myLocalUser.getObjectId());
                    MyUser testUser = new MyUser();
                    testUser.setUselessString("" + System.currentTimeMillis());
                    testUser.update(MainActivity.this, myLocalUser.getObjectId(), new UpdateListener() {
                        @Override
                        public void onSuccess() {

                        }

                        @Override
                        public void onFailure(int i, String s) {
                            Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
                            CrashReport.postCatchedException(new Throwable("code:"+i+"  "+s));  // bugly会将这个throwable上报
                            Logger.e(s);
                            if (s!=null&&s.contains("sessionToken")) {
                                BmobUser.logOut(MainActivity.this);   //清除缓存用户对象
                                startActivity(new Intent(MainActivity.this,LoginActivity.class));
                                finish();
                            }
                        }
                    });
                }else{
                    BmobUser.logOut(MainActivity.this);   //清除缓存用户对象
                    startActivity(new Intent(MainActivity.this,LoginActivity.class));
                    finish();
                }

            }
        });
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            BmobUser.logOut(MainActivity.this);   //清除缓存用户对象
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void initView() {
        myLocalUser = BmobUser.getCurrentUser(MainActivity.this, MyUser.class);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
//        toolbar_title.setText("教育");
        toolbar.setNavigationOnClickListener(view -> {
            BmobUser.logOut(MainActivity.this);   //清除缓存用户对象
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            finish();
        });
    }

    private void queryCommand() {
        RequestParams params = new RequestParams("http://heyue.oss-cn-hangzhou.aliyuncs.com/AppData/%E6%95%99%E8%82%B2MP4/command.html");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result.contains("false")) {
                    finish();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                finish();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initData() {

        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        SharePreferencesUtil.putSpString(LOGINTIME, curDate.getTime() + "", FastApp.get());

        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);//设置显示方式
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)//第三
//                .drawable(R.drawable.sample)///图片
                .drawable(R.drawable.divider)
                .size(0)
                .build());

        adapter = new BaseRecyclerAdapter<GradeBean>(this, mdata, R.layout.activity_item) {
            @Override
            public void init(BaseRecyclerViewHolder holder, GradeBean bean, int position) {
                holder.setText(R.id.tv_item, bean.getGradeName());
            }
        };
        adapter.setOnItemClickLinster(new BaseRecyclerAdapter.OnItemClickLinster() {
            @Override
            public void onItemClick(View view, int position) {
                GradeBean gradeBean = mdata.get(position);
                Boolean flagAccess = false;
                for (Integer integer : myLocalUser.getLevel()) {
                    if (integer == gradeBean.getLevel()) {
                        flagAccess = true;
                    }
                }
                if (flagAccess == true) {
                    Intent intent = new Intent(MainActivity.this, GradeActivity.class);
                    intent.putExtra("objId", gradeBean.getObjectId());
                    startActivity(intent);
                } else {
                    Toast.makeText(MainActivity.this, " 当前课程需要等级:" + gradeBean.getLevel(), Toast.LENGTH_SHORT).show();
                }

            }
        });
        recyclerView.setAdapter(adapter);//设置适配器


        BmobQuery<GradeBean> query = new BmobQuery<GradeBean>();
        query.order("index");
        query.findObjects(this, new FindListener<GradeBean>() {
            @Override
            public void onSuccess(List<GradeBean> list) {
                mdata.addAll(list);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(int i, String s) {

            }
        });


    }


}

